﻿using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Configuration;

namespace ProcDaemon
{
    public class Mail
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        public static bool SendMail(string mailBody)
        {
            string emailFromAddress = "luculentsis@163.com";
            string emailPassword = "luculent1!";

            var mailTo = ConfigurationManager.AppSettings["MailTo"];
            var toAddresses = mailTo.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (toAddresses.Count == 0)
            {
                return false;
            }

            var mailSubject = ConfigurationManager.AppSettings["MailSubject"];

            try
            {
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(emailFromAddress);
                toAddresses.ForEach(r => msg.To.Add(new MailAddress(r)));
                msg.Subject = mailSubject;
                msg.SubjectEncoding = Encoding.UTF8;

                msg.Body = mailBody;
                msg.BodyEncoding = Encoding.UTF8;
                msg.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.163.com";
                smtp.Credentials = new NetworkCredential(emailFromAddress, emailPassword);
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

                smtp.Send(msg);
                _logger.Info("邮件已发送");
            }
            catch (Exception err)
            {
                _logger.Error("邮件发送失败: {0}", err.ToString());
            }

            return true;
        }
    }
}
